package com.jshoperxms.controller.api.langdu;

import com.jshoperxms.Response;
import com.jshoperxms.components.redis.RedisUtils;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.mall.backstage.base.SearchModel;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.PrimaryKey;
import com.jshoperxms.controller.utils.RandomCodeUtil;
import com.jshoperxms.controller.utils.enums.BaseEnums;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.jshoperxms.controller.utils.statickey.TagWords;
import com.jshoperxms.controller.utils.statickey.WarnWrods;
import com.jshoperxms.entity.*;
import com.jshoperxms.service.*;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sdywcd on 2018/10/30.
 * Des:
 */
@RestController
@RequestMapping("/api/team")
public class YdTeamController extends BaseTController{

    @Resource
    private YdTeamTService ydTeamTService;

    @Resource
    private MemberTService memberTService;

    @Resource
    private YdTeamMemberTService ydTeamMemberTService;

    @Resource
    private YdArticleRecordRdTService ydArticleRecordRdTService;

    @Resource
    private YdRecordRdTService ydRecordRdTService;
    @Resource
    private RedisUtils redisUtils;


    /**
     * 加入小队
     * @param rq
     * @return
     */
    @RequestMapping(value="/joinTeam",method= RequestMethod.POST)
    public ResponseEntity joinTeam(@RequestBody YdTeamMemberT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTeamid())&&StringUtils.isNotBlank(rq.getWxopenid())){
            //检查是否加入过小队
            Criterion criterion=Restrictions.and(Restrictions.eq("wxopenid",rq.getWxopenid())).add(Restrictions.eq("teamid",rq.getTeamid()));
            YdTeamMemberT ydTeamMemberT=this.ydTeamMemberTService.findOneByCriteria(YdTeamMemberT.class,criterion);
            if(ydTeamMemberT!=null){
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,"havajoin");
            }else{
                Criterion criterion1=Restrictions.eq("wxopenid",rq.getWxopenid());
                YdTeamT teamT=this.ydTeamTService.findByPK(YdTeamT.class,rq.getTeamid());
                MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion1);
                if(teamT!=null&&memberT!=null){
                    YdTeamMemberT bean=new YdTeamMemberT();
                    bean.setId(PrimaryKey.get().toString());
                    bean.setTmnick(memberT.getNick());
                    bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                    bean.setCreatetime(DateTools.getSystemTimeLong());
                    bean.setCreatorid("0");
                    bean.setUpdatetime(DateTools.getSystemTimeLong());
                    bean.setVersiont(1);
                    bean.setMemberid(memberT.getId());
                    bean.setWxopenid(rq.getWxopenid());
                    bean.setTeamname(teamT.getTeamname());
                    bean.setTeamid(rq.getTeamid());
                    bean.setAvatarurl(memberT.getHeadpath());
                    bean.setTeamno(teamT.getTeamno());
                    bean.setMtype("0");//队员
                    this.ydTeamMemberTService.save(bean);
                    responsedata.put(TagWords.BEAN,bean);
                    responsedata.put(TagWords.SUCCESS,true);
                   // addJoinedTeamToRedis(teamT,bean);
                    //更新队员人数
                    updateTeamMemberCount(teamT);
                }else{
                    responsedata.put(TagWords.SUCCESS,false);
                    responsedata.put(TagWords.MSG,WarnWrods.EMPTY_RECORD);
                }
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }

    public void updateTeamMemberCount(YdTeamT bean){
        bean.setUpdatetime(DateTools.getSystemTimeLong());
        bean.setCurrentmember(bean.getCurrentmember()+1);
        this.ydTeamTService.update(bean);
    }

//    private void addJoinedTeamToRedis(YdTeamT team,YdTeamMemberT rq){
//        List<YdTeamT> ydTeamTS=new ArrayList<>();
//        String tk=redisUtils.getObjectByKey(RedisKey.MINETEAM+rq.getWxopenid());
//        if(tk!=null){
//            ydTeamTS = GsonJson.parseJsonToData(redisUtils.getObjectByKey(RedisKey.MINETEAM + rq.getWxopenid()), YdTeamT.class);
//            if (!ydTeamTS.isEmpty()) {
//                if (!ydTeamTS.contains(team)){
//                    ydTeamTS.add(team);
//                    redisUtils.setObjectEx(RedisKey.MINETEAM + rq.getWxopenid(), 1296000, GsonJson.parseDataToJson(ydTeamTS));
//                }
//            }
//        }else{
//            ydTeamTS.add(team);
//            redisUtils.setObjectEx(RedisKey.MINETEAM + rq.getWxopenid(), 1296000, GsonJson.parseDataToJson(ydTeamTS));
//
//        }
//
//
//    }

    /**
     * 创建公开小队伍
     * @param rq
     * @return
     */
    @RequestMapping(value="/createPublicTeam",method= RequestMethod.POST)
    public ResponseEntity createPublicTeam(@RequestBody YdTeamT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getWxopenid())&&StringUtils.isNotBlank(rq.getTeamname())&&StringUtils.isNotBlank(rq.getTeamdes())){
            Criterion criterion1=Restrictions.eq("wxopenid",rq.getWxopenid());
            MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion1);
            if(memberT!=null){
                Criterion criterion= Restrictions.eq("teamname",rq.getTeamname());
                YdTeamT teamT=this.ydTeamTService.findOneByCriteria(YdTeamT.class,criterion);
                if(teamT==null){
                    YdTeamT bean=new YdTeamT();
                    bean.setId(PrimaryKey.get().toString());
                    bean.setLeadermemberid(memberT.getId());
                    bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                    bean.setCreatetime(DateTools.getSystemTimeLong());
                    bean.setCreatorid("0");
                    bean.setUpdatetime(DateTools.getSystemTimeLong());
                    bean.setVersiont(1);
                    bean.setLeadername(memberT.getNick());
                    bean.setDayleynotice(StaticKey.EMPTY);
                    bean.setWxopenid(rq.getWxopenid());
                    bean.setTeamname(rq.getTeamname());
                    bean.setTeamdes(rq.getTeamdes());
                    bean.setType(rq.getType()+"");//公开小队是1
                    bean.setMaxmember(99);
                    bean.setCurrentmember(1);
                    bean.setTeamavatarurl(rq.getTeamavatarurl());
                    bean.setStoreid("0");
                    bean.setIsreviewed("1");
                    bean.setReviewedtime(DateTools.getSystemTimeLong());
                    bean.setTotalyuedu(0);
                    bean.setTotalleafs(0);
                    bean.setTotalshare(0);
                    bean.setTotalstrees(0);
                    bean.setHotper(0);
                    bean.setTeaminvitecode("0");//默认0表示公开的小队
                    bean.setTeamno(DateTools.getSystemTimeLong()+ RandomCodeUtil.getRandomInt()+"");
                    bean.setTeamcategory(rq.getTeamcategory());
                    bean.setTeamcategoryid(rq.getTeamcategoryid());
                    bean.setRecommend("0");//不推荐小队
                    this.ydTeamTService.save(bean);
                    responsedata.put(TagWords.BEAN,bean);
                    responsedata.put(TagWords.SUCCESS,true);
                    //把队长加入小队
                    saveLeandertoTeam(memberT,bean);
                }else{
                    responsedata.put(TagWords.SUCCESS,false);
                    responsedata.put(TagWords.MSG,WarnWrods.REPEAT_NAME);
                }
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,"nomember");
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);

        }
        return Response.success(responsedata);
    }

    private void saveLeandertoTeam(MemberT memberT,YdTeamT teamT){
        YdTeamMemberT bean=new YdTeamMemberT();
        bean.setId(PrimaryKey.get().toString());
        bean.setTmnick(memberT.getNick());
        bean.setStatus(BaseEnums.DataUsingState.USING.getState());
        bean.setCreatetime(DateTools.getSystemTimeLong());
        bean.setCreatorid("0");
        bean.setUpdatetime(DateTools.getSystemTimeLong());
        bean.setVersiont(1);
        bean.setMemberid(memberT.getId());
        bean.setWxopenid(memberT.getWxopenid());
        bean.setTeamname(teamT.getTeamname());
        bean.setTeamid(teamT.getId());
        bean.setAvatarurl(memberT.getHeadpath());
        bean.setTeamno(teamT.getTeamno());
        bean.setMtype("1");//队长
        this.ydTeamMemberTService.save(bean);

    }

    /**
     * 创建私人小队
     * @param rq
     * @return
     */
    @RequestMapping(value="/createPrivateTeam",method= RequestMethod.POST)
    public ResponseEntity createPrivateTeam(@RequestBody YdTeamT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getWxopenid())&&StringUtils.isNotBlank(rq.getTeamname())&&StringUtils.isNotBlank(rq.getTeamdes())&&StringUtils.isNotBlank(rq.getTeaminvitecode())){
            Criterion criterion1=Restrictions.eq("wxopenid",rq.getWxopenid());
            MemberT memberT=this.memberTService.findOneByCriteria(MemberT.class,criterion1);
            if(memberT!=null){
                Criterion criterion= Restrictions.eq("teamname",rq.getTeamname());
                YdTeamT teamT=this.ydTeamTService.findOneByCriteria(YdTeamT.class,criterion);
                if(teamT==null){
                    YdTeamT bean=new YdTeamT();
                    bean.setId(PrimaryKey.get().toString());
                    bean.setLeadermemberid(memberT.getId());
                    bean.setStatus(BaseEnums.DataUsingState.USING.getState());
                    bean.setCreatetime(DateTools.getSystemTimeLong());
                    bean.setCreatorid("0");
                    bean.setUpdatetime(DateTools.getSystemTimeLong());
                    bean.setVersiont(1);
                    bean.setLeadername(memberT.getNick());
                    bean.setDayleynotice(StaticKey.EMPTY);
                    bean.setWxopenid(rq.getWxopenid());
                    bean.setTeamname(rq.getTeamname());
                    bean.setTeamdes(rq.getTeamdes());
                    bean.setType("2");//私人小队是2
                    bean.setMaxmember(66);
                    bean.setCurrentmember(1);
                    bean.setTeamavatarurl(memberT.getHeadpath());
                    bean.setStoreid("0");
                    bean.setIsreviewed("1");
                    bean.setReviewedtime(DateTools.getSystemTimeLong());
                    bean.setTotalyuedu(0);
                    bean.setTotalleafs(0);
                    bean.setTotalshare(0);
                    bean.setTotalstrees(0);
                    bean.setHotper(0);
                    bean.setTeamno(DateTools.getSystemTimeLong()+ RandomCodeUtil.getRandomInt()+"");
                    bean.setTeaminvitecode(rq.getTeaminvitecode());//默认0表示公开的小队
                    bean.setTeamcategory(rq.getTeamcategory());
                    bean.setRecommend("0");
                    this.ydTeamTService.save(bean);
                    responsedata.put(TagWords.BEAN,bean);
                    responsedata.put(TagWords.SUCCESS,true);
                }else{
                    responsedata.put(TagWords.SUCCESS,false);
                    responsedata.put(TagWords.MSG,"haveteamname");
                }
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,"nomember");
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);

        }
        return Response.success(responsedata);
    }


    /**
     * 查询小队信息
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamInfoById",method= RequestMethod.POST)
    public ResponseEntity findTeamInfo(@RequestBody YdTeamT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())&&StringUtils.isNotBlank(rq.getWxopenid())){
            YdTeamT bean=this.ydTeamTService.findByPK(YdTeamT.class,rq.getId());
            if(bean!=null){
                responsedata.put(TagWords.BEAN,bean);
                responsedata.put(TagWords.SUCCESS,true);
                Criterion criterion=Restrictions.and(Restrictions.eq("teamid",rq.getId())).add(Restrictions.eq("wxopenid",rq.getWxopenid()));
                YdTeamMemberT ydTeamMemberT=this.ydTeamMemberTService.findOneByCriteria(YdTeamMemberT.class,criterion);
                if(ydTeamMemberT!=null){
                    responsedata.put("isjointeam",true);
                }else{
                    responsedata.put("isjointeam",false);
                }
            }else{
                responsedata.put(TagWords.SUCCESS,false);
                responsedata.put(TagWords.MSG,WarnWrods.EMPTY_RECORD);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG, WarnWrods.ERROR_PARAMS);
        }

        return Response.success(responsedata);

    }


    /**
     * 查询小队首页数据
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamIndexResult",method= RequestMethod.POST)
    public ResponseEntity findTeamIndexResult(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        int currentPage=rq.getStart();
        int lineSize=rq.getLength();
        if(StringUtils.equals("all",rq.getTeamcategory())){
            Criterion criterion=Restrictions.and(Restrictions.eq("recommend","1")).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("type","1"));
            int recrods=this.ydTeamTService.count(YdTeamT.class,criterion).intValue();
            List<YdTeamT> list=this.ydTeamTService.findByCriteriaByPage(YdTeamT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
            rq.setRecordsTotal(recrods);
            responsedata.put("results",list);
            responsedata.put("start",rq.getNextPageNo());
            responsedata.put("totalPage",rq.getTotalPage());
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            Criterion criterion=Restrictions.and(Restrictions.eq("teamcategory",rq.getTeamcategory())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("type","1"));
            int recrods=this.ydTeamTService.count(YdTeamT.class,criterion).intValue();
            List<YdTeamT> list=this.ydTeamTService.findByCriteriaByPage(YdTeamT.class,criterion, Order.desc(TagWords.CREATETIME),currentPage,lineSize);
            rq.setRecordsTotal(recrods);
            responsedata.put("results",list);
            responsedata.put("start",rq.getNextPageNo());
            responsedata.put("totalPage",rq.getTotalPage());
            responsedata.put(TagWords.SUCCESS,true);
        }

        return Response.success(responsedata);

    }


    /**
     * 获取推荐的小队内图文朗读内容公开到小队页面
     * @return
     */
    @RequestMapping(value="/findTeamRecommendArtsResults",method= RequestMethod.POST)
    public ResponseEntity findRecommendResults(){
        Map<String,Object> responsedata=new HashMap<>();
        Criterion criterion= Restrictions.and(Restrictions.eq("recommend","1")).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
        List<YdArticleRecordRdT>list=this.ydArticleRecordRdTService.findByCriteriaByPage(YdArticleRecordRdT.class,criterion, Order.desc(TagWords.UPDATETIME),1,8);
        responsedata.put("results",list);
        responsedata.put(TagWords.SUCCESS,true);
        return Response.success(responsedata);
    }


    /**
     * 获取小队的一起读的图文内容
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamArtRecords",method= RequestMethod.POST)
    public ResponseEntity findTeamArtRecords(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTeamid())){
            Criterion criterion= Restrictions.and(Restrictions.eq("draft","0")).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState())).add(Restrictions.eq("teamid",rq.getTeamid()));
            List<YdArticleRecordRdT>list=this.ydArticleRecordRdTService.findByCriteriaByPage(YdArticleRecordRdT.class,criterion, Order.desc(TagWords.CREATETIME),1,100);
            responsedata.put("results",list);
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }

        return Response.success(responsedata);
    }

    /**
     * 查询会员读
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamArtMemberReads",method= RequestMethod.POST)
    public ResponseEntity findTeamArtMemberReads(@RequestBody SearchModel rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getTeamid())){
            Criterion criterion=Restrictions.and(Restrictions.eq("teamid",rq.getTeamid())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
            List<YdRecordRdT>list=this.ydRecordRdTService.findByCriteriaByPage(YdRecordRdT.class,criterion,Order.desc(TagWords.UPDATETIME),1,100);
            responsedata.put("results",list);
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
        }
        return Response.success(responsedata);
    }


    /**
     * 更新小队内容总分享
     * @param teamid
     */
    public void updateTeamContentSharesCount(String teamid){
        YdTeamT bean=this.ydTeamTService.findByPK(YdTeamT.class,teamid);
        if(bean!=null){
            bean.setHotper(bean.getHotper()+1);
            bean.setTotalshare(bean.getTotalshare()+1);
            bean.setUpdatetime(DateTools.getSystemTimeLong());
            bean.setVersiont(bean.getVersiont()+1);
            this.ydTeamTService.update(bean);
        }
    }

    /**
     * 更新小队的总内容数量
     * @param teamid
     */
    public void updateTeamContentCount(String teamid){
        YdTeamT bean=this.ydTeamTService.findByPK(YdTeamT.class,teamid);
        if(bean!=null){
            bean.setTotalleafs(bean.getTotalleafs()+50);
            bean.setHotper(bean.getHotper()+1);
            bean.setTotalyuedu(bean.getTotalyuedu()+1);
            bean.setUpdatetime(DateTools.getSystemTimeLong());
            bean.setVersiont(bean.getVersiont()+1);
            this.ydTeamTService.update(bean);
        }
    }


    /**
     * 查询小队成员
     * @param rq
     * @return
     */
    @RequestMapping(value="/findTeamMembers",method= RequestMethod.POST)
    public ResponseEntity findTeamMembers(@RequestBody YdTeamT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            Criterion criterion=Restrictions.and(Restrictions.eq("teamid",rq.getId())).add(Restrictions.eq(TagWords.STATUS, BaseEnums.DataUsingState.USING.getState()));
            List<YdTeamMemberT>list=this.ydTeamMemberTService.findByCriteria(YdTeamMemberT.class,criterion);
            responsedata.put("results",list);
            responsedata.put(TagWords.SUCCESS,true);
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


    /**
     * 更新小队信息
     * @param rq
     * @return
     */
    @RequestMapping(value="/updatePublicTeamInfo",method= RequestMethod.POST)
    public ResponseEntity updatePublicTeamInfo(@RequestBody YdTeamT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            YdTeamT bean=this.ydTeamTService.findByPK(YdTeamT.class,rq.getId());
            if(bean!=null){
                bean.setUpdatetime(DateTools.getSystemTimeLong());
                bean.setVersiont(bean.getVersiont()+1);
                bean.setTeamdes(rq.getTeamdes());
                bean.setTeamavatarurl(rq.getTeamavatarurl());
                bean.setTeamname(rq.getTeamname());
                this.ydTeamTService.update(bean);
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }

    /**
     * 退出小队
     * @param rq
     * @return
     */
    @RequestMapping(value="/exitTeam",method= RequestMethod.POST)
    public ResponseEntity exitTeam(@RequestBody YdTeamT rq){
        Map<String,Object> responsedata=new HashMap<>();
        if(StringUtils.isNotBlank(rq.getId())){
            Criterion criterion=Restrictions.and(Restrictions.eq("wxopenid",rq.getWxopenid())).add(Restrictions.eq("teamid",rq.getId()));
            YdTeamMemberT ydTeamMemberT=this.ydTeamMemberTService.findOneByCriteria(YdTeamMemberT.class,criterion);
            if(ydTeamMemberT!=null){
                ydTeamMemberT.setStatus(BaseEnums.DataUsingState.DEL.getState());
                ydTeamMemberT.setVersiont(ydTeamMemberT.getVersiont()+1);
                this.ydTeamMemberTService.update(ydTeamMemberT);
                responsedata.put(TagWords.SUCCESS,true);
            }
        }else{
            responsedata.put(TagWords.SUCCESS,false);
            responsedata.put(TagWords.MSG,WarnWrods.ERROR_PARAMS);
        }
        return Response.success(responsedata);
    }


}
